import React, { FC, useCallback, useState } from 'react';
import QuestionCard from './components/QuestionCard';
import { produce } from 'immer';
import './List3.css';
const data = [
  { id: 'q1', title: '问卷1', isPublished: true },
  { id: 'q2', title: '问卷2', isPublished: false },
  { id: 'q3', title: '问卷3', isPublished: true },
  { id: 'q4', title: '问卷4', isPublished: false },
  { id: 'q5', title: '问卷5', isPublished: true },
  { id: 'q6', title: '问卷6', isPublished: false },
];
let id = data.length;
const List1: FC = () => {
  const [questionList, setQuestionList] = useState(data);
  const deleteQuestion = useCallback(
    (id: string) => {
      // setQuestionList(questionList.filter((question) => question.id !== id));
      setQuestionList(
        produce(questionList, (draft) => {
          const index = draft.findIndex((q) => q.id === id);
          if (index !== -1) {
            draft.splice(index, 1);
          }
        })
      );
    },
    [questionList]
  );
  const publicQuestion = useCallback(
    (id: string, flag: boolean) => {
      // setQuestionList(
      //   questionList.map((question) =>
      //     question.id === id ? { ...question, isPublished: flag } : question
      //   )
      // );
      setQuestionList(
        produce(questionList, (draft) => {
          const index = draft.findIndex((q) => q.id === id);
          if (index !== -1) {
            draft[index].isPublished = flag;
          }
        })
      );
    },
    [questionList]
  );
  return (
    <div>
      <h1>问卷列表页</h1>
      <div>
        {questionList.map((question) => {
          const { id, title, isPublished } = question;
          return (
            <React.Fragment key={id}>
              <QuestionCard
                id={id}
                title={title}
                isPublished={isPublished}
                deleteQuestion={deleteQuestion}
                publicQuestion={publicQuestion}
              />
            </React.Fragment>
          );
        })}
      </div>
      <button
        onClick={() => {
          let uid = ++id;
          // setQuestionList([
          //   ...questionList,
          //   {
          //     id: `q${uid}`,
          //     title: `问卷${uid}`,
          //     isPublished: Math.random() > 0.5,
          //   },
          // ]);
          setQuestionList(
            produce(questionList, (draft) => {
              draft.push({
                id: `q${uid}`,
                title: `问卷${uid}`,
                isPublished: Math.random() > 0.5,
              });
            })
          );
        }}
      >
        addItem
      </button>
    </div>
  );
};
export default List1;
